package com.yanqu.road.web.interceptor;

import com.alibaba.fastjson.JSON;
import com.yanqu.road.entity.admin.AdminResult;
import com.yanqu.road.server.manger.WhiteIpMgr;
import com.yanqu.road.utils.config.Config;
import com.yanqu.road.web.util.IpAddressHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

//注意是单例
public class SimpleInterceptor implements HandlerInterceptor {

    private static Logger logger = LogManager.getLogger(SimpleInterceptor.class.getName());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("后台接口 {},参数{}", request.getRequestURI(), JSON.toJSONString(request.getParameterMap()));
        //简单先做，ip白名单
        String ipAddr = IpAddressHelper.getIpAddr(request);
        String produceType = "application/json;charset=UTF-8";
        if(!WhiteIpMgr.isAdminWhiteIp(ipAddr) && !Config.isDebug()){
            WhiteIpMgr.getLogger().error("ip:{}", ipAddr);
            boolean isReloadWhiteIp = false;

            if(handler.getClass().isAssignableFrom(HandlerMethod.class)){
                HandlerMethod hm = (HandlerMethod)handler;
                Method method = hm.getMethod();
                RequestMapping annotation = method.getAnnotation(RequestMapping.class);
                if(annotation != null){
                    if(method.getName().equals("reloadMgr")){
                        if(method.getParameterCount() == 3){
                            String name = method.getParameters()[2].getName();
                            String parameter = request.getParameter(name);
                            if("WhiteIpMgr".equals(parameter)){
                                isReloadWhiteIp = true;
                            }
                        }
                    }
                    for (String produce : annotation.produces()) {
                        produceType = produce;
                        break;
                    }
                }
            }

            //如果是刷白名单，则不过过滤
            if(!isReloadWhiteIp) {

                response.setCharacterEncoding("utf-8");
                response.setContentType(produceType);
                response.setHeader("Access-Control-Allow-Origin", "*");
                try {
                    response.getWriter().write(AdminResult.failCode(-1, "IP Illegal!").toJsonString());
                    response.getWriter().flush();
                    response.getWriter().close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        if(ex != null){
            logger.error("", ex);
        }
    }
}
